package com.example.securityconfig.entity.enums;

import lombok.Getter;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
 
/**
 * @ClassName ExceptionCodeEnum
 * @Author zhangzhixi
 * @Description 通用错误枚举（不同类型的错误也可以拆成不同的Enum细分）
 * @Date 2022-4-7 18:19
 * @Version 1.0
 */
@Getter
public enum ExceptionCodeEnum {
    /**
     * 通用结果
     */
    ERROR(-1, "网络错误!"),
    SUCCESS(200, "成功!"),
 
    /**
     * 用户
     */
    NEED_LOGIN(900, "用户未登录!"),
    SECURITY_ERROR(401,"用户认证失败,请登录!"),
    ROOT_ERROR(401,"用户权限不足!"),
    TOKEN_EXPIRED(401, "token过期或为空!"),
    USER_EXIST(409, "用户已存在!"),
    USER_NOT_EXIST(404, "用户不存在!"),
    PASSWORD_ERROR(401, "密码错误!"),


    /**
     * 参数校验
     */
    ERROR_PARAM(10000, "参数错误"),
    EMPTY_PARAM(10001, "参数为空"),
    ERROR_PARAM_LENGTH(10002, "参数长度错误"),

    /**
     * 请求接口方法错误
     */
    ERROR_SHOULD_POST(405,"HTTP请求方法应为POST"),
    ERROR_SHOULD_GET(405,"HTTP请求方法应为GET");
    private final Integer code;
    private final String msg;
 
    ExceptionCodeEnum(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }
 
    private static final Map<Integer, ExceptionCodeEnum> ENUM_CACHE = new HashMap<>();
 
    static {
        for (ExceptionCodeEnum exceptionCodeEnum : ExceptionCodeEnum.values()) {
            ENUM_CACHE.put(exceptionCodeEnum.code, exceptionCodeEnum);
        }
    }
 
    public static String getDesc(Integer code) {
        return Optional.ofNullable(ENUM_CACHE.get(code))
                .map(ExceptionCodeEnum::getMsg)
                .orElseThrow(() -> new IllegalArgumentException("invalid exception code!"));
    }
}